package com.stooges.adjustment.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.stooges.adjustment.entity.LoginLog;
import com.stooges.adjustment.entity.Role;
import com.stooges.adjustment.form.OauthForm;
import com.stooges.adjustment.form.RegistForm;
import com.stooges.adjustment.service.LoginService;
import com.stooges.adjustment.util.Constants;
import com.stooges.adjustment.util.Md5Util;
import com.stooges.adjustment.util.SimpleValidator;
import com.stooges.adjustment.util.WebUtil;
import com.stooges.adjustment.view.OauthView;

/**
 * 登录注册控制器
 * @author 张超
 *
 */
@Controller
public final class LoginController {
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	@Resource
	private LoginService loginService;
	/**
	 * 判断session中是否有值，有值的话直接
	 * @param session
	 * @return
	 */
	@RequestMapping(value={"/toLogin","/"})
	public String toLogin(HttpServletRequest request,HttpSession session){
		OauthView oauth = (OauthView) session.getAttribute(Constants.SESSION_USER);
		if(oauth==null){
			//查询cookies中是否有登录信息
			String uid = WebUtil.getCookieValueByName(request, Constants.COOKIE_UID);
			String token = WebUtil.getCookieValueByName(request, Constants.COOKIE_TOKEN);
			if(!StringUtils.isEmpty(uid) && !StringUtils.isEmpty(token)){
				LoginLog loginLog = new LoginLog();
				try {
					loginLog.setLocalOauthId(Long.valueOf(uid));
				} catch (NumberFormatException e) {
					e.printStackTrace();
					log.error(e.getMessage(),e);
					return "error/404";
				}
				loginLog.setToken(token);
				oauth = loginService.findOauthByLoged(loginLog);
				if(oauth == null){
					return "login";
				}
			}else{
				return "login";
			}
		}
		Role role = oauth.getRole();
		//管理员
		if(role.getId()==1){
			return "admin/index";
		}
		//学院
		else if(role.getId()==2){
			return "college/index";
		}
		//教师 3：可以开账户  4：不可以开账户
		else if(role.getId()==3 || role.getId()==4){
			return "teacher/index";
		}
		//学生
		else if(role.getId()==5){
			return "student/index";
		}else{
			return "login";
		}
	}
	/**
	 * 根据用户输入的用户名及密码进行登录
	 * @param oauthForm 用户输入的用户名及密码
	 * @param session
	 * @param modelMap 数据
	 * @return 处理完要返回的页面
	 */
	@RequestMapping("/login")
	public String login(OauthForm oauthForm,HttpServletResponse response,HttpSession session,ModelMap modelMap){
		//对于已经登录的直接跳转到主页面
		OauthView sesOauth = (OauthView) session.getAttribute(Constants.SESSION_USER);
		if(sesOauth!=null){
			Role role = sesOauth.getRole();
			//管理员
			if(role.getId()==1){
				return "admin/index";
			}
			//学院
			else if(role.getId()==2){
				return "college/index";
			}
			//教师 3：可以开账户  4：不可以开账户
			else if(role.getId()==3 || role.getId()==4){
				return "teacher/index";
			}
			//学生
			else if(role.getId()==5){
				return "student/index";
			}else{
				return "login";
			}
		}
		
		//判断用户名密码输入是否正确
		if(oauthForm==null || SimpleValidator.isBlank(oauthForm.getUsername())||SimpleValidator.isBlank(oauthForm.getPassword())){
			modelMap.put("error", "用户名或密码错误");
			return "login";
		}
		else{
			//根据用户输入的数据查找数据库中用户信息
			OauthView dbOauth = loginService.findOauthByInput(oauthForm.getUsername());
			if(dbOauth==null || !dbOauth.getPassword().equals(Md5Util.MD5(oauthForm.getPassword()))){
				modelMap.put("error", "用户名或密码错误");
				return "login";
			}else{
				Integer maxAge = null;
				//写入登录日志
				LoginLog loginLog = new LoginLog();
				loginLog.setLocalOauthId(dbOauth.getId());
				if(oauthForm.isRemeber()){
					maxAge = 2*30*24*60*60;
				}else{
					maxAge = 24*60*60;
				}
				loginLog.setExpires(System.currentTimeMillis()/1000+maxAge);
				loginService.saveLoginLog(loginLog);
				
				//判断用户登录名与登录密码正确后将数据放在session中
				session.setAttribute(Constants.SESSION_USER, dbOauth);
				if(oauthForm.isRemeber()){
					WebUtil.addCookie(response, Constants.COOKIE_UID, dbOauth.getId().toString(),maxAge);
					WebUtil.addCookie(response, Constants.COOKIE_TOKEN,loginLog.getToken(),maxAge);
				}else{
					WebUtil.addCookie(response, Constants.COOKIE_UID, dbOauth.getId().toString());
					WebUtil.addCookie(response, Constants.COOKIE_TOKEN,loginLog.getToken());
				}
				Role role = dbOauth.getRole();
				//管理员
				if(role.getId()==1){
					return "admin/index";
				}
				//学院
				else if(role.getId()==2){
					return "college/index";
				}
				//教师 3：可以开账户  4：不可以开账户
				else if(role.getId()==3 || role.getId()==4){
					return "teacher/index";
				}
				//学生
				else if(role.getId()==5){
					return "student/index";
				}else{
					return "login";
				}
			}
		}
	}
	/**
	 * 去注册
	 * @return
	 */
	@RequestMapping("/toRegist")
	public String toRegist(){
		return "regist";
	}
	/**
	 * 注册
	 * @param registForm 注册表单
	 * @param attrs  跳转的属性
	 * @param modelMap 
	 * @return
	 */
	@RequestMapping("/regist")
	public String regist(RegistForm registForm,RedirectAttributes attrs,ModelMap modelMap){
		Map<String,String> errorMap = new HashMap<String,String>();
		if(registValidate(registForm, errorMap)){
			//去除注册信息中的空字符
			trimRegistForm(registForm);
			//将注册信息保存到数据库
			boolean regist = loginService.regist(registForm);
			if(regist){
				String username = registForm.getTicketNumber();
				if(Character.isDigit(username.charAt(0))){
					username = "U"+username;
				}
				attrs.addFlashAttribute("username", username);
				attrs.addFlashAttribute("password", registForm.getPassword());
				OauthForm oauthForm = new OauthForm();
				oauthForm.setUsername(username);
				oauthForm.setPassword(registForm.getPassword());
				attrs.addFlashAttribute("oauthForm", oauthForm);
				//跳转到自动登录
				return "redirect:/login";
			}else{
				String error="注册失败，请稍后重试";
				modelMap.put("error", error);
				return "regist";
			}
		}else{
			modelMap.put("error", errorMap.get("error"));
			return "regist";
		}
	}
	/**
	 * 登出
	 * @param session
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletResponse response,HttpSession session){
		session.removeAttribute(Constants.SESSION_USER); 
		WebUtil.removeCookie(response, "uid");
		WebUtil.removeCookie(response, "token");
		return "login";
	}
	/**
	 * 注册验证
	 * @param registForm 注册表单
	 * @param error 错误
	 * @return
	 */
	private boolean registValidate(RegistForm registForm,Map<String,String> errorMap){
		if(registForm==null){
			errorMap.put("error","请完整填写注册表单");
			return false;
		}else{
			//非空验证
			if(SimpleValidator.isBlank(registForm.getTel())){
				errorMap.put("error","请输入手机号");
				return false;
			}else if(SimpleValidator.isBlank(registForm.getTicketNumber())){
				errorMap.put("error","请输入准考证号");
				return false;
			}else if(SimpleValidator.isBlank(registForm.getIdcard())){
				errorMap.put("error","请输入身份证号");
				return false;
			}else if(SimpleValidator.isBlank(registForm.getEmail())){
				errorMap.put("error","请输入邮箱");
				return false;
			}else if(SimpleValidator.isBlank(registForm.getPassword())){
				errorMap.put("error","请输入密码");
				return false;
			}
			//正确性验证
			if(!SimpleValidator.isMobile(registForm.getTel())){
				errorMap.put("error","请输入正确的手机号");
				return false;
			}else if(!SimpleValidator.isValidatedIdcard(registForm.getIdcard())){
				errorMap.put("error","请输入正确的身份证号码");
				return false;
			}else if(!SimpleValidator.isEmail(registForm.getEmail())){
				errorMap.put("error","请输入正确的邮箱");
				return false;
			}else if(registForm.getPassword().trim().length()<6||registForm.getPassword().trim().length()>15){
				errorMap.put("error","请输入6-15位数字、字母、特殊字符组成的密码");
				return false;
			}
			
			//判断手机号、身份证、邮箱、准考证是否已经被注册
			return !loginService.validateDuplicate(registForm,errorMap);
		}
	}
	/**
	 * 去除注册表单的空字符
	 * @param registForm
	 */
	private void trimRegistForm(RegistForm registForm){
		registForm.setEmail(registForm.getEmail().trim());
		registForm.setIdcard(registForm.getIdcard().trim());
		registForm.setPassword(registForm.getPassword().trim());
		registForm.setTel(registForm.getTel().trim());
		registForm.setTicketNumber(registForm.getTicketNumber().trim());
	}
}
